<template>
  <div class="menu-item" :style="levelStyle" :class="{ active }" @click="clickCurrent">
    <slot name="icon">
      <div class="collapse" :class="{ expand }">
        <iconfont
          v-if="showCollapse"
          :size="20"
          icon="right"
          type="btn"
          @click="visible = !visible"
        ></iconfont>
      </div>
    </slot>
    <div class="title">{{ menu.title }}</div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { realRoutes } from '@/router/routes'

export default {
  name: 'MenuItem',
  props: {
    menu: {
      type: Object,
      default: () => ({}),
    },
    showCollapse: {
      type: Boolean,
      default: false,
    },
    expand: {
      type: Boolean,
      default: false,
    },
    level: {
      type: Number,
      default: 0,
    },
  },
  emits: ['update:expand'],
  setup(props, { emit }) {
    const visible = computed({
      get: () => props.expand,
      set: val => emit('update:expand', val),
    })
    const levelStyle = computed(() => ({ paddingLeft: `${props.level * 24}px` }))
    const router = useRouter()
    const route = useRoute()

    const active = computed(() => route.name === props.menu.name)

    function clickCurrent() {
      if (props.menu.name === 'home') {
        router.push('/')
        return
      }
      const isRoute = realRoutes.find(i => i.name === props.menu.name)
      if (isRoute) {
        router.push({ path: isRoute.path })
      } else {
        visible.value = !visible.value
      }
    }

    return {
      visible,
      levelStyle,
      active,
      clickCurrent,
    }
  },
}
</script>

<style lang="stylus" scoped>
.menu-item {
  display: flex;
  align-items: center;
  overflow: hidden;
  border-radius: 6px;
  height: 34px;
  border: 1px solid rgba(0,0,0,0);
  color: #262626;
  padding-right: 6px;
  padding-left: 0;
  cursor: pointer;
  margin-bottom: 2px;
  &:hover,&.active {
    background-color: #eff0f0;
    border: 1px solid #eff0f0;
  }
  &.active .title {
    font-weight: 700;
  }
  .collapse {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 6px;
    margin-right: 4px;
    :deep(.icon-wrapper){
      transition: .35s ease-in-out;
      > i {
        transition: .2s ease-in-out;
      }
      &:hover {
        background-color: #d8dad9;
      }
    }
    &.expand {
      :deep(.icon-wrapper){
        > i {
          transform: rotate(90deg);
        }
      }
    }
  }
  .title {
    display: flex;
    flex: 1;
    align-items: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
